package it.blueocean.acanto.platform.web;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ui.ModelMap;

public abstract class ABaseAcantoFilteredController
{
	private final static Logger logger = LoggerFactory.getLogger(ABaseAcantoFilteredController.class);

	public abstract String defaultDispatcher(HttpServletRequest request);
	
	public abstract String newItem(ModelMap model);
	
	public abstract String delete(String[] deleteIds, ModelMap model);
	
	public abstract String list();
	
	public abstract String getSessionFilterName();

	/**
	 * Retrieve Request values "filterName" and "filterValue" by
	 * @RequestParam("filterName") and @RequestParam("filterValue") annotations.
	 * The Request method must be setted in POST as follow :
	 * 
	 * @RequestMapping(method = RequestMethod.POST, value = [.....] )
	 * 
	 * @param filterName
	 * @param filterValue
	 * @param session
	 * @param request
	 * @return
	 */
	public abstract String simpleFilter(String filterName, String filterValue, HttpSession session, HttpServletRequest request);

	/**
	 * The Request method must be setted in GET as follow :
	 * 
	 * @RequestMapping(method = RequestMethod.GET, value = [.....] )
	 * 
	 * @param session
	 * @return
	 */
	public abstract String resetFilter(HttpSession session);

	protected final String getPreferredResolution(HttpServletRequest request)
	{
		String referrerPage = request.getHeader("Referer");

		int i = request.getHeader("Referer").lastIndexOf("/");
		String str3 = referrerPage.substring(0, i + 1);

		String redirectUrl = request.getParameter("__acanto_redirect");
		String forwardUrl = request.getParameter("__acanto_forward");

		if(logger.isDebugEnabled())
		{
			logger.debug("\nPreferred resolution parameters are:\nredirectUrl : " + ((redirectUrl == null) ? "null" : redirectUrl)
					+ "\n" + "forwardUrl : " + ((forwardUrl == null) ? "null" : forwardUrl) + "\n" + "currentPath : "
					+ ((str3 == null) ? "null" : str3) + "\n");
		}

		if(forwardUrl != null)
		{
			if(forwardUrl.startsWith("/"))
			{
				return "forward:" + forwardUrl;
			}

			return "forward:" + str3 + forwardUrl;
		}

		if(redirectUrl != null)
		{
			if(redirectUrl.trim().equals(""))
			{
				return "redirect:" + referrerPage;
			}
			if(redirectUrl.startsWith("/"))
			{
				return "redirect:" + redirectUrl;
			}

			return "redirect:" + str3 + redirectUrl;
		}
		
		return referrerPage;
	}

}
